const xlsx = require("xlsx")
const fs = require("fs")
const path = require("path");

const xlsxFile = path.resolve(__dirname, '../static/xlsx')
/**
 *
 * @param {Array} data
 * @param {{parentKey: string, idKey: string, childrenKey: string,order: string}} options
 * @return {*}
 */
exports.listToTree = function (data, options) {
    options = options || {};
    var ID_KEY = options.idKey || 'id';
    var PARENT_KEY = options.parentKey || 'parent_id';
    var CHILDREN_KEY = options.childrenKey || 'children';
    var ORDER = options.order || "menu_order"
    var tree = [],
        childrenOf = {};
    var item, id, parentId;

    // 首先，将每个项映射到父ID下
    for (var i = 0, length = data.length; i < length; i++) {
        item = data[i];
        id = item[ID_KEY];
        parentId = item[PARENT_KEY] || 0;
        // 每个parentId都初始化一个子数组
        childrenOf[parentId] = childrenOf[parentId] || [];
        // 在子数组中添加当前项
        childrenOf[parentId].push(item);
    }

    // 利用递归函数来形成树形结构
    function formTree(parentId) {
        var children = childrenOf[parentId];
        if (!children) {
            return null;
        }
        // 对子节点数组进行排序
        children.sort(function(a, b) {
            return (a[ORDER] || 0) - (b[ORDER] || 0);
        });
        for (var i = 0, length = children.length; i < length; i++) {
            var child = children[i];
            // 递归调用 formTree 函数，子节点为当前节点的id
            var childTree = formTree(child[ID_KEY]);
            if (childTree) {
                // 如果存在子树，则在当前节点上添加子树
                child[CHILDREN_KEY] = childTree;
            }
        }
        return children;
    }

    // 返回树的根节点数组
    return formTree(0); // 开始构造从根节点开始的树形结构
}
const $ = (date) => {
    const $Y = date.getFullYear()
    const $M = date.getMonth()
    const $D = date.getDate()
    const $W = date.getDay()
    const $H = date.getHours()
    const $m = date.getMinutes()
    const $s = date.getSeconds()
    const $ms = date.getMilliseconds()
    return {
        $Y,
        $M,
        $D,
        $W,
        $H,
        $m,
        $s,
        $ms
    }
}

const numToCapital = (num, type = 0) => {
    const numString = num.toString()
    if (numString.length) {
        // 有逗号去掉逗号
        const strNum = Number((num + '').replace(/[,，]*/g, '')) + ''
        let capitalAr = '零一二三四五六七八九十'
        let unitAr = ['十', '百', '千', '万', '十', '百', '千', '亿', '十', '百', '千']
        if (type === 1) {
            capitalAr = '零壹贰叁肆伍陆柒捌玖拾'
            unitAr = ['拾', '佰', '仟', '万', '拾', '佰', '仟', '亿', '拾', '佰', '仟'] // 单位
        }
        // 转换为整数
        const numNumber = parseInt(strNum)
        let index = strNum.length - 1 //记录位数
        let idx = 0 // 记录单位
        let percent = 10
        const arr = []

        const turnNum = (num, percent, index) => {
            const unit = num / percent
            const capital = capitalAr[Number(strNum[index])]
            if (unit < 1) {
                arr.push(capital)
                // 出现11【一十一】这种情况
                if (
                    Number(strNum[index]) === 1 &&
                    (strNum.length === 2 || strNum.length === 6 || strNum.length === 10)
                ) {
                    arr.pop()
                }
                // 结束递归
                return false
            }else {
                if (capital === '零') {
                    // 万和亿单位不删除
                    if (!['万', '亿'].includes(arr[arr.length - 1])) {
                        arr.pop()
                    }
                    // 前面有零在删掉一个零
                    if (arr[arr.length - 1] === '零') {
                        arr.pop()
                    }
                }
                arr.push(capital)
                // 过滤存在【零万】【零亿】这种情况
                if (['万', '亿'].includes(arr[arr.length - 2]) && capital === '零') {
                    arr.pop()
                }
                // 过滤【1亿万】这种情况
                if (arr[0] === '万' && arr[1] === '亿') {
                    arr.shift()
                }
                // 末尾【零】删掉
                if (arr[0] === '零') {
                    arr.pop()
                }
                arr.push(unitAr[idx++])
                turnNum(num, percent * 10, --index)
            }
        }
        turnNum(numNumber, percent, index)
        return arr.reverse().join('')
    }
    return ''
}
exports.numToCapital = numToCapital
exports.format = (str, type = 'YYYY-MM-DD HH:mm:ss') => {
    const dateStr = String(str).toLocaleString()
    const time = str ? new Date(dateStr) : new Date()
    const regexp =  /\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g
    const { $Y, $M, $D, $W, $H, $m, $s, $ms } = $(time)
    const matches = {
        // 年 后两位
        YY: String($Y).slice(-2),
        //  年
        YYYY: String($Y),
        // 月
        M: String($M + 1),
        // 月补0
        MM: String($M + 1).padStart(2, '0'),
        // 日
        D: String($D),
        // 日补0
        DD: String($D).padStart(2, '0'),
        // 1
        d: String($W),
        // 周一
        dd: String(numToCapital($W)).padStart(2 , '周'),
        // 星期一
        ddd: String(numToCapital($W)).padStart(3 , '星期'),
        // 24小时
        H: String($H),
        HH: String($H).padStart(2, '0'),
        // 12小时
        h: String($H % 12),
        hh: String($H % 12).padStart(2, '0'),
        // 分
        m: String($m),
        mm: String($m).padStart(2, '0'),
        // 秒
        s: String($s),
        ss: String($s).padStart(2, '0'),
        // 毫秒
        sss: String($ms).padStart(3, '0')
    }

    return type.replace(regexp, (match, i) => {
        return i || matches[match]
    })
}

// 进制转换
function decimalToBase62(decimal, type = 62) {
    const baseChars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    let result = '';

    do {
        result = baseChars[decimal % type] + result;
        decimal = Math.floor(decimal / type);
    } while (decimal > 0);

    return result;
}
exports.message = (num) => {
    switch (num) {
        case 500:
            return {
                message: '系统错误',
                code: 500,
                data
            }
        case 400:
            return {
                message: '系统错误',
                code: 400,
                data
            }
    }
}

/**
 * 随机生成手机号码
 * @return {string}
 */
function generateRandomPhoneNumber() {
    var prefix = ['130', '131', '132', '133', '134', '135', '136', '137', '138', '139',
        '150', '151', '152', '153', '155', '156', '157', '158', '159',
        '180', '181', '182', '183', '184', '185', '186', '187', '188', '189'];
    var randomPrefix = prefix[Math.floor(Math.random() * prefix.length)];
    var randomSuffix = Math.random().toString().slice(2, 10);
    return randomPrefix + randomSuffix;
}
exports.generateRandomPhoneNumber = generateRandomPhoneNumber


// 根据id 获取下面的所有节点
exports.listToObj = function (data, options, id) {

}